﻿# Textures.py: textures module
# 02/06/09 - 2013
# Copyright(c) 2009 Victor Freire e Cássio Espindola. All rights reserved.
# Python 2.6.2
import pygame
import os
from warnings import *

class TextureManager:
    def __init__(self):
        self.DEFAULT_PATH = os.path.join(os.curdir, "data", "textures")
        self.TEXTURE_LIST_PATH = os.path.join(self.DEFAULT_PATH, "texlist.dat")
        self.tex_surfaces = {} #dict, texture name -> texture surface
        
    
    
    def get_texture(self, ttype, name):
        realname = os.path.join(ttype, name)
        try:
            return self.tex_surfaces[realname]
        except KeyError:
            if self.load_texture(realname):
                return self.tex_surfaces[realname]
            else:
                warn(("Warning: requested texture -%s- not found! Using default..." % realname))
                return self.tex_surfaces["default"]
                
        
    def load_texture(self, name):
        ''' Loads the desired texture. Returns False on error. '''
        try:
            newtex = pygame.image.load(os.path.join(self.DEFAULT_PATH, (name + '.png'))).convert()
            self.tex_surfaces[name] = newtex
            return True
        except:
            return False
    
    def load_textures(self):
        ''' Loads all the textures in texlist.dat. '''
        # First, load the default texture
        if not self.load_texture("default"):
            warn("Couldn't load default texture!")

        numberloaded = 0
        
        try:
            texlist = open(self.TEXTURE_LIST_PATH)
        except:
            warn(("Error: failed to load - %s - loading on the fly..." % self.TEXTURE_LIST_PATH))
            return numberloaded
            
        newtype = None
        
        for i in texlist.readlines():
            if i[0] == '-':
                newtype = i[1:]
            elif not i.isspace():
                if newtype and self.load_texture(os.path.join(newtype, i)):
                    numberloaded += 1 #loaded another texture successfully
                else:
                    break
        
        texlist.close()
        return numberloaded

Textures = TextureManager()


